package com.yuhao.common.strcount.log_20191219;

import com.google.common.collect.Maps;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class LogResolvUtil {

    /** 提供私有构造器让编译器别默认实例化该类 */
    private LogResolvUtil() {
    }

    /** 获取所有lo路径下以.log为后缀的文件*/
    public static List<LogFile> getFileNames() {
        String path = "D:\\数据迁移日志\\log\\log";
        File file = new File(path);
        String[] arr = file.list();
        List<LogFile> list = new ArrayList<>();
        for (String string : arr) {
            if (string.endsWith(".LOG")) {
                list.add(LogFile.builder().tableName("\"" + string.split("_")[0] + "_" + string.split("_")[1] + "\"")
                        .tablePartitionName(string.split("\\.")[0])
                        .logFilePath(path + "\\" + string)
                        .build());
            }
        }
        return list;
    }

    /** 获取每行的row值*/
    public static long subStrToLong(String str, String start, String end) {
        int startIndex = str.indexOf(start);
        int endIndex = str.indexOf(end);
        String result = str.substring(startIndex + 2, endIndex).trim();
        return Long.parseLong(result);
    }

    /** 获取每行的size值*/
    public static double subStrToDouble(String str, String start, String end) {
        int startIndex = str.indexOf(start);
        int endIndex = str.indexOf(end);
        String result = str.substring(startIndex + 1, endIndex).trim();
        return Double.parseDouble(result);
    }

    /**获取每行字符串list*/
    public static List<String> toArrayByFileReader1(String name) {
        // 使用ArrayList来存储每行读取到的字符串
        List<String> arrayList = new ArrayList<>();
        try (FileReader fr = new FileReader(name);BufferedReader bf = new BufferedReader(fr)) {
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                arrayList.add(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    /** 获取所有地区编码*/
    public static String subStrAreacode(String str, String start, String end) {
        int startIndex = str.indexOf(start);
        String str1 = str.substring(startIndex + 2);
        int endIndex = str1.indexOf(end);
        String result = str.substring(startIndex + 2, startIndex + endIndex + 2);
        return result;
    }

    // 解析logFile的集合
    public static List<LogFile> logResolv(List<LogFile> list, String resolvReg) {
        DecimalFormat decimalFormat = new DecimalFormat("#.0000");
        for (LogFile e : list) {
            long index = 0L;
            BigDecimal bigDecimal = BigDecimal.valueOf(0.00);
            List<String> fileStrs = toArrayByFileReader1(e.getLogFilePath());
            for (int i = 0; i < fileStrs.size(); i++) {
                String e1 = fileStrs.get(i);
                if (e1.indexOf("ORA-") != -1) {
                    System.out.println("表"+e.getTableName()+"的分区"+e.getTablePartitionName()+"有ORA异常");
                    continue ;
                }
                if (e1.indexOf(e.getTableName()) != -1) {
                    long strLong = 0L;
                    BigDecimal strBigD = new BigDecimal(0);
                    if (e1.indexOf("GB") != -1) {
                        strLong = subStrToLong(e1, "GB", resolvReg);
                        strBigD = BigDecimal.valueOf(subStrToDouble(e1, "\"  ", "GB") * 1024);
                    } else if (e1.indexOf("MB") != -1) {
                        strLong = subStrToLong(e1, "MB", resolvReg);
                        strBigD = BigDecimal.valueOf(subStrToDouble(e1, "\"  ", "MB"));
                    } else if (e1.indexOf("KB") != -1) {
                        strLong = subStrToLong(e1, "KB", resolvReg);
                        strBigD = BigDecimal.valueOf(subStrToDouble(e1, "\"  ", "KB") / 1024);
                    }
                    bigDecimal = bigDecimal.add(strBigD);
                    index += strLong;
                }
            }
            e.setSize(BigDecimal.valueOf(Double.parseDouble(decimalFormat.format(bigDecimal))));
            e.setRows(index);
        }
        return list;
    }

    /** 按格式汇总*/
    public static Map<String, String> countInfo(List<LogFile> list) {
        // 定义格式
        DecimalFormat decimalFormat = new DecimalFormat("#.0000");
        Map<String, String> map = Maps.newHashMap();
        // 获取list中所有tablename去重结果
        List<String> tableNameList = list.stream().map(LogFile::getTableName).distinct().collect(Collectors.toList());
        // 遍历并累加
        for (String str : tableNameList) {
            long countRows = list.stream().filter(e -> e.getTableName().equals(str)).mapToLong(LogFile::getRows).sum();
            BigDecimal countSize = list.stream().filter(e -> e.getTableName().equals(str)).map(LogFile::getSize).reduce(
                    BigDecimal.ZERO, BigDecimal::add
            );
            map.put(str, "rows: " + countRows + ", size:" + decimalFormat.format(countSize.doubleValue()));
        }
        return map;
    }

    /** 输出按用户的参数文件*/
    public static void outToFile(List<String> strList, List<String> partitionStrList) {
        String oraUser = "PMS_SC_GD";
        for (String str : strList) {
            StringBuffer dumpFile = new StringBuffer();
            for (String partitionStr : partitionStrList) {
                if (partitionStr.indexOf(str) != -1)
                    dumpFile.append(partitionStr+"_%U.DMP"+",");
            }
            String filePath = "D:\\数据迁移日志\\log\\user-param\\"+oraUser +"_"+ str+".par";
            String newDumpFile = dumpFile.substring(0, dumpFile.length()-1);
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("directory=kfzx_dir\n");
            stringBuffer.append("dumpfile="+newDumpFile+"\n");
            stringBuffer.append("parallel=8\n");
            stringBuffer.append("cluster=n\n");
            stringBuffer.append("transform=segment_attributes:n\n");
            stringBuffer.append("content=data_only\n");
            stringBuffer.append("remap_schema=pms_sc:"+oraUser+"_"+str+"\n");
            stringBuffer.append("table_exists_action=truncate\n");
            stringBuffer.append("exclude=statistics,index,grant,ref_constraint,constraint\n");
            stringBuffer.append("logfile="+oraUser+"_"+str+".txt\n");
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                outputStream.write(stringBuffer.toString().getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
